package com.jiangyg.mall.core.support.web;

import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 类描述：HTTP请求包装类
 * <p>可以多次使用 request.getInputStream() 方法读取请求体内容</p>
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-11
 */
@Slf4j
public class MutilReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 请求体内容
     */
    private final byte[] body;

    public MutilReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = WebUtils.readBodyToBytes(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {

            final ByteArrayInputStream bis = new ByteArrayInputStream(body);

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() throws IOException {
                return bis.read();
            }

        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

}
